<?php

error_reporting(E_STRICT | E_ALL);
date_default_timezone_set('America/New_York');
ini_set('display_errors', 1);
set_time_limit(60*30);

require_once "config.php";
require_once dirname(__FILE__). '/util/connection.class.php';

$g_start = microtime(true);

$dbconn = Connection::getInstance();

function getSites(Connection $db)
{
	$sql = "SELECT id, domain FROM `sites` ";
	try{
		$ret = $db->query($sql);
		return $ret;
	}catch (Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}

function getTokenUsers(Connection $db, $site_id, $tokenAmount)
{
	$sql = "SELECT u.id, SUM(r.credit) AS total_t, u.gender, u.birthday, u.won FROM `users` AS u LEFT JOIN `rewards` AS r ON u.id=r.user_id WHERE u.site_id=? GROUP BY u.id HAVING total_t>=? ORDER BY total_t DESC ";
	try{
		$ret = $db->query($sql, array($site_id, $tokenAmount));
		return $ret;
	}catch (Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}

$sites = getSites($dbconn);
//$restoredSites = array();
//foreach ($sites as $site) {
//	if ($site['domain'] == 'lalaloot.com' || $site['domain'] == 'cashdazzle.com')
//		$restoredSites['id'] = $site['id'];
//		$restoredSites['domain'] = $site['domain'];
//}

/*
$users = array(
	array('id'=>1078, 'total_t'=>156, 'gender'=>'F', 'birthday'=>'1980-12-05', 'won'=>'31.75'),
	array('id'=>37660, 'total_t'=>148, 'gender'=>'M', 'birthday'=>'1988-03-03', 'won'=>'40.95'),
	array('id'=>8937, 'total_t'=>100, 'gender'=>'F', 'birthday'=>'1960-02-16', 'won'=>'32.95'),
);
*/
/*
$users = array(
			array('id'=>1078, 'total_t'=>156, 'gender'=>'F', 'birthday'=>'1980-12-05', 'won'=>'31.75'),
			array('id'=>37660, 'total_t'=>148, 'gender'=>'M', 'birthday'=>'1988-03-03', 'won'=>'40.95'),
			array('id'=>8937, 'total_t'=>100, 'gender'=>'F', 'birthday'=>'1960-02-16', 'won'=>'32.95'),
		);
		echo (microtime(true)-$g_start) . "\tcashdazzle\t". count($users). " users\n";
		$resortedusers = resortUsers($users);
		echo (microtime(true)-$g_start) . "\tcashdazzle\tresort users\n";
		$collectedUsers = collectUserTokenData($resortedusers);
		echo (microtime(true)-$g_start) . "\tcashdazzle\tcollect users\n";
		writeToFile($collectedUsers, 'cashdazzle', $dbconn);
		die();
*/

foreach ($sites as $site) {
	if ($site['domain'] == 'lalaloot.com') {
		$users = getTokenUsers($dbconn, $site['id'], 50);
		
		echo (microtime(true)-$g_start) . "\tlalaloot\t". count($users). " users\n";
		$resortedusers = resortUsers($users);
		echo (microtime(true)-$g_start) . "\tlalaloot\tresort users\n";
		$collectedUsers = collectUserTokenData($resortedusers);
		echo (microtime(true)-$g_start) . "\tlalaloot\tcollect users\n";
		writeToFile($collectedUsers, 'lalaloot', $dbconn);
		
	}
/*	elseif ($site['domain'] == 'cashdazzle.com') {
		$users = getTokenUsers($dbconn, $site['id'], 15);
		
		echo (microtime(true)-$g_start) . "\tcashdazzle\t". count($users). " users\n";
		$resortedusers = resortUsers($users);
		echo (microtime(true)-$g_start) . "\tcashdazzle\tresort users\n";
		$collectedUsers = collectUserTokenData($resortedusers);
		echo (microtime(true)-$g_start) . "\tcashdazzle\tcollect users\n";
		writeToFile($collectedUsers, 'cashdazzle', $dbconn);
	}
*/
}

/*

$users = array(1=>array('domain'=>'lalaloot.com', 'token'=>50, 'sessions'=>array(
	'session_id' => array('start'=>0, 'end'=>0, 'played'=>0,),), 'fullfillement'=>0
));
*/

function collectUserTokenData($users) {
	$rootDir = RAW_DATA_ROOT; //.'/'. date('Y_m', time());
	if (!file_exists($rootDir))
	{
		mkdir($rootDir, 0600, true);
	}
	chdir($rootDir);
	foreach (glob("*_*") as $dirname) {
		if (is_dir($dirname)) {
			chdir($rootDir . '/' . $dirname);
			foreach (glob("*_*") as $filename) {
				$handler = fopen($rootDir . '/' . $dirname . '/' . $filename, 'r');
				if ($handler) {
					while (!feof($handler)) {
						$line = fgets($handler);
						if (!empty($line)) {
							$args = explode(':', $line);
							if (!empty($args[0]) && !empty($args[2]) && !empty($args[3]) && !empty($args[4]) && !empty($args[11]))
							{
								$time = $args[0];
								$sessionId = $args[2];
								$uid = $args[3];
								$event = $args[4];
								$site = $args[11];
								if (isset($users[$uid])) {
									if (!isset($users[$uid]['sessions']) || !isset($users[$uid]['sessions'][$sessionId])) {
										$currentSessionStat = array('start'=>$time, 'end'=>$time, 'played'=>0, 'fullreg'=>0, 'token'=>0, 'offer'=>0);
									}  else {
										$currentSessionStat = $users[$uid]['sessions'][$sessionId];
										$currentSessionStat['end'] = $time;
									}
									if ($event == 'played' || $event == 'reward' || $event == 'full_reg') {
										if ($event == 'played') {
											$currentSessionStat['played'] += 1;
										} elseif ($event == 'reward') {
											if (isset($args[19])) {
												$token = $args[19];
											} else {
												$token = 0;
											}
											$currentSessionStat['token'] += $token;
											$currentSessionStat['offer'] += 1;
										} elseif ($event == 'full_reg') {
											$currentSessionStat['fullreg'] += 1;
										}
									}
									$users[$uid]['sessions'][$sessionId] = $currentSessionStat;
								}
							}
						}
					}
				}
				fclose($handler);
			}
			chdir($rootDir);
		}
	}
	return $users;
}

function writeToFile($users, $site, $dbconn) {
	$dirname = dirname(__FILE__);
	$filename = $dirname.'/'. $site . '_statbysession';
	$filename2 = $dirname.'/'. $site . '_statbydate';
	$file = fopen($filename, "w+");
	$file2 = fopen($filename2, 'w+');
	foreach ($users as $uid => $user) {
		//$log = "User ID\tGender\tBirthday\tWon\tTotal Token\n";
		//$log .= $uid . "\t" . $user['gender'] . "\t" . $user['birthday'] . "\t" . $user['won'] . "\t" . $user['total_t'] . "\n";
//		$log = "User ID\tSession ID\tSession Start\tSession End\tTotal Played That Session\tFull Reg\n";
		$log = '';
		
		if (!empty($user['sessions'])) {
			foreach ($user['sessions'] as $sessionId => $session) {
				$log .= $uid . "\t" . $sessionId . "\t" . date('Y-m-d H:i:s', $session['start']) . "\t" . date('Y-m-d H:i:s', $session['end']) . "\t" . $session['played']
					 . "\t" . $session['fullreg'] . "\n";
			}
		}
		if (!empty($user['sessions']))
		{
			$mergedSessions = mergedWithinOneDay($user['sessions']);
		}
		$tokens = resortRewardsToken($uid, $dbconn);
/*		if (!empty($mergedSessions)) {
			foreach ($mergedSessions as $date => $mergedSession) {
				$token = 0;
				if (isset($tokens[$date])) {
					$token = $tokens[$date]['credit'];
					unset($tokens[$date]);
				}
				if ($mergedSession['played'] || $mergedSession['offer'] || $token) {
					$log .= $date . "\t" . $mergedSession['offer'] ."\t" . $token . "\n";
				}
			}
		}
		
*/		
		$log .= "\n";
		fwrite($file, $log);
		
		
//		$log2 = "User ID\tDate\tOffer Completed\tToken Earned\n";
		$log2 = '';
		if (count($tokens) > 0) {
			foreach ($tokens as $date => $dailyToken) {
				$log2 .= $uid . "\t" . $date . "\t" . $dailyToken['offer'] ."\t" . $dailyToken['credit'] . "\n";
			}
		}
		$log2 .= "\n";
		fwrite($file2, $log2);
		unset($user[$uid]);
	}
}

function resortUsers($users) {
	$resortedUsers = array();
	foreach ($users as $user) {
		$id = $user['id'];
		unset($user['id']);
		$resortedUsers[$id] = $user;
	}
	return $resortedUsers;
}

function mergedWithinOneDay($sessions) {
	$temp = array();
	foreach ($sessions as $session) {
		$date = date('Y-m-d', $session['start']);
		if (isset($temp[$date])) {
			$temp[$date]['token'] += $session['token'];
			$temp[$date]['offer'] += $session['offer'];
		} else {
			unset($session['start'], $session['end']);
			$temp[$date] = $session;
		}
	}
	return $temp;
}

function getRewardsToken($uid, $db) {
	$sql = "SELECT credit, created from `rewards` where user_id=? ";
	try{
		$ret = $db->query($sql, array($uid));
		return $ret;
	}catch (Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}

function resortRewardsToken($uid, $db) {
	$tokens = getRewardsToken($uid, $db);
//	var_dump($uid);
//	var_dump($tokens);
	$temp = array();
	if (count($tokens) > 0) {
		foreach ($tokens as $token) {
			$date = date('Y-m-d', $token['created']);
			if (isset($temp[$date])) {
				$temp[$date]['credit'] += $token['credit'];
				$temp[$date]['offer'] ++;
			} else {
				$temp[$date]['credit'] = $token['credit'];
				$temp[$date]['offer'] = 1;
			}
		}
	}
//	var_dump($temp);
	return $temp;
}
